package com.yuke.cloud.service.cmc.controller.frontend;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.base.constant.GlobalConstant;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.pmc.dto.ProdSpecInfoExDto;
import com.yuke.cloud.service.api.pmc.service.PmcFeignApi;
import com.yuke.cloud.service.api.wmc.exceptions.WmcBizException;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.cmc.dto.CmsAppIds;
import com.yuke.cloud.service.cmc.dto.CmsSpecDto;
import com.yuke.cloud.service.cmc.entity.CmsAppTopicData;
import com.yuke.cloud.service.cmc.entity.CmsSysInfo;
import com.yuke.cloud.service.cmc.service.CmsAppTopicDataService;
import com.yuke.cloud.service.cmc.service.CmsSysInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* Created by wg on 2019/01/18.
*/
@Api(value = "WEB - CmsAppTopicDataController", tags = "处理CmsAppTopicData相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/cms/app_topic_data")
public class CmsAppTopicDataController extends BaseController {
    @Resource
    private CmsAppTopicDataService cmsAppTopicDataService;
    @Resource
    private CmsSysInfoService cmsSysInfoService;
    @Resource
    private PmcFeignApi pmcFeignApi;
    @Resource
    private WmcStorageFeignApi wmcStorageFeignApi;

    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "cmsAppTopicData", value = "该数据记录的POJO") @RequestBody CmsAppTopicData cmsAppTopicData) {
        cmsAppTopicData.setDataId(super.generateId());
        cmsAppTopicDataService.save(cmsAppTopicData);
        return WrapMapper.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        cmsAppTopicDataService.deleteById(id);
        return WrapMapper.ok();
    }

    @PostMapping("/ids")
    @ApiOperation(httpMethod = "POST", value = "批量删除")
    public Wrapper deleteByIds(@ApiParam(name = "ids", value = "该数据记录的POJO") @RequestBody CmsAppIds cmsAppIds) {
        cmsAppTopicDataService.deleteByIds(cmsAppIds.getIds());
        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "cmsAppTopicData", value = "需要修改的内容") @RequestBody CmsAppTopicData cmsAppTopicData) {
        cmsAppTopicDataService.update(cmsAppTopicData);
        return WrapMapper.ok();
    }

    @PutMapping("/updateList")
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper updateList(@ApiParam(name = "cmsAppTopic", value = "需要修改的内容") @RequestBody List<CmsAppTopicData> cmsAppTopicDatas) {
        cmsAppTopicDataService.updateList(cmsAppTopicDatas);
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<CmsAppTopicData> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id,
                                           @ApiParam(name = "isPassByChildTopic", value = "是否为子主题的数据") @RequestParam(required = false) Boolean isPassByChildTopic) {
        CmsAppTopicData cmsAppTopicData = cmsAppTopicDataService.findById(id, isPassByChildTopic);
        return WrapMapper.ok(cmsAppTopicData);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<CmsAppTopicData>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                    @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<CmsAppTopicData> list = cmsAppTopicDataService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    @PostMapping("/ifExist")
    @ApiOperation(httpMethod = "POST", value = "检查唯一性")
    public Wrapper ifExist(@ApiParam(name = "cmsAppTopic", value = "记录topicName") @RequestBody CmsAppTopicData cmsAppTopicData) {
        int count = cmsAppTopicDataService.selectCount(cmsAppTopicData);
        return WrapMapper.ok(count);
    }

    @PostMapping("/condition")
    @ApiOperation(httpMethod = "POST", value = "分页获取所有记录")
    public Wrapper<PageInfo<CmsAppTopicData>> listByCondition(@ApiParam(name = "cmsAppTopic", value = "根据主题名称查找") @RequestBody(required = false) CmsAppTopicData cmsAppTopicData,
                                                          @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                          @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<CmsAppTopicData> list = cmsAppTopicDataService.listByCondition(cmsAppTopicData);
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    @PostMapping("/pointGoods")
    @ApiOperation(httpMethod = "POST", value = "根据条件获取积分换兑list")
    public Wrapper<List<ProdSpecInfoExDto>> getpointGoods( @RequestBody CmsSpecDto cmsSpecDto) {
        //todo 系统信息分部门\按类型查找
        Example example = new Example(CmsSysInfo.class);
        Example.Criteria criteria = example.createCriteria();

        Long shopId = cmsSpecDto.getShopId();
        Long shopGroupId = 220839532667469824L;
        Wrapper wrap = wmcStorageFeignApi.getGroupIdByShopId(shopId);
        if (wrap.getCode() == 200 && wrap.getResult() != null ){
            shopGroupId = Long.valueOf(wrap.getResult().toString());
        }

        criteria.andEqualTo("groupId",shopGroupId);
        criteria.andEqualTo("sysInfoType", GlobalConstant.SysInfo.SYS_INFO_POINT_GO);
        List<CmsSysInfo> cmsSysInfo = cmsSysInfoService.selectByExample(example);
        if (PublicUtil.isEmpty(cmsSysInfo)){
            return WrapMapper.error("查询系统信息参数错误！");
        }
        List<ProdSpecInfoExDto> prodSpecInfoExDtoList = this.getPointTopicGoods(cmsSysInfo.get(0),cmsSpecDto.getShopId(),1);
        if (PublicUtil.isEmpty(prodSpecInfoExDtoList)){
            return WrapMapper.error("查询结果为空！");
        }
        return WrapMapper.ok(prodSpecInfoExDtoList);
    }

    @PostMapping("/pointMixGoods")
    @ApiOperation(httpMethod = "POST", value = "根据条件获取积分换兑list")
    public Wrapper<List<ProdSpecInfoExDto>> getpointMixGoods( @RequestBody CmsSpecDto cmsSpecDto) {
        //todo 系统信息分部门\按类型查找
        Example example = new Example(CmsSysInfo.class);
        Example.Criteria criteria = example.createCriteria();

        Long shopId = cmsSpecDto.getShopId();
        Long shopGroupId = 220839532667469824L;
        Wrapper wrap = wmcStorageFeignApi.getGroupIdByShopId(shopId);
        if (wrap.getCode() == 200 && wrap.getResult() != null ){
            shopGroupId = Long.valueOf(wrap.getResult().toString());
        }

        criteria.andEqualTo("groupId",shopGroupId);
        criteria.andEqualTo("sysInfoType", GlobalConstant.SysInfo.SYS_INFO_POINT_MIX_GO);
        List<CmsSysInfo> cmsSysInfo = cmsSysInfoService.selectByExample(example);

        if (PublicUtil.isEmpty(cmsSysInfo)){
            return WrapMapper.error("查询系统信息参数错误！");
        }
        List<ProdSpecInfoExDto> prodSpecInfoExDtoList = this.getPointTopicGoods(cmsSysInfo.get(0),cmsSpecDto.getShopId(),2);
        if (PublicUtil.isEmpty(prodSpecInfoExDtoList)){
            return WrapMapper.error("查询结果为空！");
        }
       return WrapMapper.ok(prodSpecInfoExDtoList);
    }

    private List<ProdSpecInfoExDto> getPointTopicGoods(CmsSysInfo cmsSysInfo, Long shopId,Integer getType){
        CmsAppTopicData cmsAppTopicData = new CmsAppTopicData();
        cmsAppTopicData.setTopicId(Long.parseLong(cmsSysInfo.getInfoValue()));

        List<ProdSpecInfoExDto> prodSpecInfoExDtoList = new ArrayList<>();
        List<CmsAppTopicData> list = cmsAppTopicDataService.select(cmsAppTopicData);
        if ( list!= null && list.size()>0){
            List<Long> specIds = list.stream().map(CmsAppTopicData::getItemId).collect(Collectors.toList());

            prodSpecInfoExDtoList = wmcStorageFeignApi.getStorageSpecBySpecIds(shopId, specIds,(byte)1);
            //List<StorageSpecInfoDto> prodSpecInfoExDtoList = wmcStorageFeignApi.getProdStorageSpecBySpecIds(specIds,shopId);
            if (PublicUtil.isEmpty(prodSpecInfoExDtoList) || prodSpecInfoExDtoList.size()<1 ){
                throw new WmcBizException(ErrorCodeEnum.WMC100500020);
            }

            //todo 系统信息分部门\按类型查找
            Example example = new Example(CmsSysInfo.class);
            Example.Criteria criteria = example.createCriteria();

            Long shopGroupId = 220839532667469824L;
            Wrapper wrap = wmcStorageFeignApi.getGroupIdByShopId(shopId);
            if (wrap.getCode() == 200 && wrap.getResult() != null ){
                shopGroupId = Long.valueOf(wrap.getResult().toString());
            }

            criteria.andEqualTo("groupId",shopGroupId);
            criteria.andEqualTo("sysInfoType", GlobalConstant.SysInfo.SYS_INFO_POINT_REBATE);
            List<CmsSysInfo> cmsSysInfoList = cmsSysInfoService.selectByExample(example);
            //end
            if (PublicUtil.isEmpty(cmsSysInfoList)){
                logger.info("系统信息查询失败！");
                return null;
            }

            float rate = Float.valueOf(cmsSysInfoList.get(0).getInfoValue());
            if (getType.toString().equals("1")){
                for(ProdSpecInfoExDto storageSpecInfoDto : prodSpecInfoExDtoList){
                    storageSpecInfoDto.setSalePrice(Math.round(storageSpecInfoDto.getSalePrice()*rate*100));
                }
            }else{
                for(ProdSpecInfoExDto storageSpecInfoDto : prodSpecInfoExDtoList){
                    storageSpecInfoDto.setSalePrice(Math.round((storageSpecInfoDto.getSalePrice()-storageSpecInfoDto.getStockPrice())*rate*100));
                }
            }


        }
        return prodSpecInfoExDtoList;
    }

}
